package post

import (
	"community-service/cmd/api/internal/models/model"
	"community-service/cmd/api/internal/svc"
	"community-service/cmd/api/internal/types"
	e "community-service/pkg/errorx"
	"context"
	"google.golang.org/grpc/codes"
	"gorm.io/gorm"
	"strings"

	user "gitee.com/vzerx/proto-contracts/auth"
	"github.com/zeromicro/go-zero/core/logx"
)

type UserCreatePostLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserCreatePostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserCreatePostLogic {
	return &UserCreatePostLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserCreatePostLogic) UserCreatePost(req *types.UserPostCreateReq) (resp *types.Empty, err error) {

	// 检查话题是否存在
	var topic model.CsCommunityTopic
	if err = l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityTopic{}).
		Where("id = ?", req.TopicId).Find(&topic).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	if topic.ID == 0 {
		return nil, e.NewGrpcErr(codes.NotFound, e.TopicNotFound)
	}

	// 检查话题所属专栏是否已发布
	var menu model.CsCommunityMenu
	if err = l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityMenu{}).
		Where("id = ? AND publish = ?", topic.MenuID, true).Find(&menu).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	if menu.ID == 0 {
		return nil, e.NewGrpcErr(codes.NotFound, e.MenuNotFound)
	}

	// 获取用户信息
	userInfo, err := l.svcCtx.User.GetUserInfo(l.ctx, &user.UserInfoReq{
		UserId: req.UserId,
	})
	if err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	if userInfo == nil || userInfo.UserId == 0 {
		return nil, e.NewGrpcErr(codes.NotFound, e.ErrorNotFound)
	}

	// 根据话题类型确定帖子状态
	// 0审批后发布 1无需审批 2禁止发布
	var status int32
	switch topic.Type {
	case types.TopicTypeAudit:
		status = types.PostTypePending
	case types.TopicTypePublic:
		status = types.PostTypeShelved
	case types.TopicTypeForbidden:
		return nil, e.NewGrpcErr(codes.PermissionDenied, e.PostPermission) // 禁止发布
	default:
		status = types.PostTypePending
	}

	// 创建帖子
	post := &model.CsCommunityPost{
		TopicID:        req.TopicId,
		Title:          strings.TrimSpace(req.Title),
		Content:        req.Content,
		Status:         status,
		IsTopped:       false,
		IsSelected:     false,
		IsOfficial:     false,
		ViewCount:      0,
		CreateUser:     req.UserId,
		CreateUsername: userInfo.UserName,
	}

	if err = l.svcCtx.DB.WithContext(l.ctx).Transaction(func(tx *gorm.DB) error {
		if err = tx.Model(&model.CsCommunityPost{}).Create(post).Error; err != nil {
			return err
		}
		// 实验映射
		if req.Experiment != nil {
			if err = tx.Create(&model.CsCommunityPostExperimentMap{
				ExperimentID:     req.Experiment.Id,
				PostID:           post.ID,
				ExperimentName:   req.Experiment.Name,
				CourseResourceID: req.Experiment.CourseResourceId,
				ChapterRefID:     req.Experiment.ChapterRefId,
			}).Error; err != nil {
				return err
			}
		}
		return nil
	}); err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	return &types.Empty{}, nil
}
